//
//  AppDelegate.m
//  Save_Archive_ CoreData_File
//
//  Created by shaorui on 15/9/5.
//  Copyright (c) 2015年 Save_Archive_ CoreData_File. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    插入数据
    [self insertUserInfoData];
    NSLog(@"insertUserInfoData-------------------------------------------");
//    查询数据
    [self dataFetchRequest];
    NSLog(@"dataFetchRequest-------------------------------------------");

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

//保存数据到持久层

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
//Documents目录路径 返回的数据目录
- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.archive--Write-File.Save_Archive__CoreData_File" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//被管理的数据模型
//
//初始化必须依赖.momd文件路径，而.momd文件由.xcdatamodeld文件编译而来


- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Save_Archive__CoreData_File" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

//持久化存储助理
//
//初始化必须依赖NSManagedObjectModel，之后要指定持久化存储的数据类型，默认的是NSSQLiteStoreType，即SQLite数据库；并指定存储路径为Documents目录下，以及数据库名称



- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Save_Archive__CoreData_File.sqlite"];//储存指定的路径下
    NSLog(@"storeURLstoreURLstoreURLstoreURLstoreURL%@",storeURL);
    
    
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

    //初始化的后，必须设置持久化存储助理

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
    //创建数据上下文，调用insertNewObjectForName方法，创建两个数据记录NSManagedObject，然后就可以对之前数据模型编辑视图中定义的属性进行赋值。此时的数据只在内存中被修改，最后调用数据上下文的save方法，保存到持久层


//测试插入数据 InsertUserInfoData
-(void)insertUserInfoData
{
//    找到应用的 managedObjectContext 
    
    NSManagedObjectContext * managedObjectContext = [self managedObjectContext];
//    找到自己的实体抽象类  USERINFO
    
    NSManagedObject * manageObjectUSERINFO =  [NSEntityDescription insertNewObjectForEntityForName:@"USERINFO" inManagedObjectContext:managedObjectContext];
    
//    @property (nonatomic, retain) NSString * userName;
//    @property (nonatomic, retain) NSString * userAge;
//    @property (nonatomic, retain) NSString * userBrithday;
//    @property (nonatomic, retain) NSString * userRemark;
//    @property (nonatomic, retain) NSString * userSex;
//    
    [manageObjectUSERINFO setValue:@"wondersgroup" forKey:@"userName"];
    [manageObjectUSERINFO setValue:@"50岁" forKey:@"userAge"];
    [manageObjectUSERINFO setValue:@"1993-12-19" forKey:@"userBrithday"];
    [manageObjectUSERINFO setValue:@"男" forKey:@"userSex"];
    [manageObjectUSERINFO setValue:@"IOS研发工程师" forKey:@"userRemark"];

    
    NSManagedObject *manageObjectUSERINFODeatil = [NSEntityDescription insertNewObjectForEntityForName:@"USERINFODTEAIL" inManagedObjectContext:managedObjectContext];
    
//    @property (nonatomic, retain) NSString * userDepartment;
//    @property (nonatomic, retain) NSString * userLike;
//    @property (nonatomic, retain) NSString * userNumber;
//    @property (nonatomic, retain) USERINFO *backUSERINFO;

    [manageObjectUSERINFODeatil setValue:@"员工编号cq136" forKey:@"userNumber"];
    [manageObjectUSERINFODeatil setValue:@"写代码" forKey:@"userLike"];
    [manageObjectUSERINFODeatil setValue:@"社保事业部" forKey:@"userDepartment"];
    
    [manageObjectUSERINFODeatil setValue:manageObjectUSERINFO forKey:@"backUSERINFO"];
    [manageObjectUSERINFO setValue:manageObjectUSERINFODeatil forKey:@"toUserDetail"];
    

    
    NSError *error;
    if(![managedObjectContext save:&error])
        {
            NSLog(@"不能保存：%@",[error localizedDescription]);
        }
    
    
    
    
    
    
}
//在调用了insertCoreData之后，可以调用自定的查询方法dataFetchRequest来查询插入的数据


- (void)dataFetchRequest
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USERINFO" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    
    
    for (NSManagedObject *info in fetchedObjects) {
        
        NSLog(@"name:%@", [info valueForKey:@"userName"]);
        NSLog(@"userBrithday:%@", [info valueForKey:@"userBrithday"]);
        NSLog(@"userSex:%@", [info valueForKey:@"userSex"]);
        NSManagedObject *details = [info valueForKey:@"toUserDetail"];
        
        NSLog(@"toUserDetail:%@", [details valueForKey:@"userLike"]);


        NSLog(@"USERINFODTEAILUSERINFODTEAILUSERINFODTEAILUSERINFODTEAIL:%@", [details valueForKey:@"userLike"]);

    }
}



@end
